package com.dingjian.framework.interceptor;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dingjian.basedata.org.model.Org;
import com.dingjian.basedata.org.model.Position;
import com.dingjian.basedata.person.model.Person;
import com.dingjian.basedata.util.SystemUtil;
import com.dingjian.framework.exception.NotLoginException;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private Set<String> excludePath = new HashSet<String>();
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();
		HttpSession session = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest().getSession();
		if(!excludePath.contains(path)){
			if(session.getAttribute("LOGIN-USER")==null){
				//普通请求
				if(request.getHeader("x-requested-with")==null){
					String port = request.getLocalPort()==80?"":":"+request.getLocalPort();
					path = request.getScheme()+"://"+request.getServerName()+port+request.getContextPath()+"/login";
					response.sendRedirect(path);
					return false;
				}else{
					throw new NotLoginException("OUTOF-LOGIN");
				}
			}
		}
		SystemUtil.setCurrentUser((Person) session.getAttribute("LOGIN-USER"));
		SystemUtil.setCurrentControlUnit((Org) session.getAttribute("CURRENT-CU"));
		SystemUtil.setCurrentOrg((Org) session.getAttribute("CURRENT-ORG"));
		SystemUtil.setCurrentPosition((Position) session.getAttribute("CURRENT-POSITION"));
		return super.preHandle(request, response, handler);
	}
	
	public void setExcludePath(String[] paths){
		if(paths!=null){
			for(String s : paths){
				excludePath.add(s);
			}
		}
	}
}
